#
# Copyright 2009 Jeffrey Palm
#

require 'util'
require 'player'

# Instances of this class are based on an Apple Script interface to
# ITunes and they implement the Player interface
class AppleScriptPlayer < Player

  # Applescript to print out the currently-playing itunes track
  ITUNES_SCRIPT = "tell application \"iTunes\"\n" +
    "	set t to current track\n" +
    "	(player state as string) & \"	\" & (artist of t) & \"	\" & (name of t) & \"	\" & (album of t) & \"	\" & (player position) & \"	\" & (track number of t) & \"	\" & (duration of t)\n" +
    "end tell\n"

  # Applescript to play the track with passed in track id
  PLAY_SCRIPT = "on run argv\n" +
    "	tell application \"iTunes\"\n" +
    "		set the_id to item 1 of argv as number\n" +
    "		activate\n" +
    "		set t to some track whose database ID is the_id\n" +
    "		play t\n" +
    "	end tell\n" +
    "end run\n"

  # Applescript to pause/play itunes
  PAUSE_SCRIPT = "on run argv\n" +
    "	tell application \"iTunes\"\n" +
    "		pause\n" +
    "	end tell\n" +
    "end run\n"

  def read_info(user)
    parts = run_script ITUNES_SCRIPT
    return {
      'state'    => get_state(parts.shift),
      'artist'   =>           parts.shift,
      'track'    =>           parts.shift,
      'album'    =>           parts.shift,
      'time'     =>           parts.shift,
      'user'     =>           user
    }
  end

  def play_track(track_id)
    run_script PLAY_SCRIPT,[track_id]
  end

  def pause
    run_script PAUSE_SCRIPT
  end

  private

  # Returns PLAYING or PAUSED for itunes PLAYING is returned unless we
  # are playing in tunes -- i.e. paused, stopped are the same
  def get_state(s)
    return PLAYING if s =~ /kPSP/ || s =~ /play/
    return PAUSED  if s =~ /kPSp/ || s =~ /paus/ #retarded!!!
    return s
  end

end
